<!--
 * @Description: 新增GWP版本弹框
 * @Author: qingyang
 * @Date: 2022-03-23 17:10:03
 * @LastEditors: qingyang
 * @LastEditTime: 2023-06-30 14:47:43
-->
<template>
  <CDialog
    class="gwp-dialog"
    :title="gwpId ? '修改GWP版本' : '新增GWP版本'"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
  >
    <el-scrollbar height="60vh" v-loading="pageLoading" ref="scrollbarRef">
      <el-form ref="formRef" :model="taskForm" :rules="rules" label-position="top" :inline="true">
        <div class="content-header">
          <span class="g-font-14n1b500">基础信息</span>
        </div>
        <el-row class="edit-container">
          <el-col :span="24">
            <el-form-item label="GWP版本：" prop="gwpCode">
              <el-select
                v-model="taskForm.gwpCode"
                filterable
                placeholder="请选择GWP版本"
                clearable
              >
                <el-option
                  v-for="item in versionList"
                  :key="item.gwpCode"
                  :label="item.gwpName"
                  :value="item.gwpCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="content-header"> <span class="g-font-14n1b">气体详情</span> </div>
        <el-row class="edit-container">
          <el-col :span="12">
            <el-form-item label="CO₂气体GWP值：" prop="coGwp">
              <el-input
                v-model="taskForm.coGwp"
                clearable
                placeholder="请输入"
                v-positive-only:5
                type="number"
                @wheel.stop.prevent
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="CH₄气体GWP值：" prop="chGwp">
              <el-input
                v-model="taskForm.chGwp"
                clearable
                placeholder="请输入"
                v-positive-only:5
                @wheel.stop.prevent
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="N₂O气体GWP值：" prop="noGwp">
              <el-input
                v-model="taskForm.noGwp"
                clearable
                placeholder="请输入"
                v-positive-only:5
                type="number"
                @wheel.stop.prevent
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SF₆气体GWP值：" prop="sfGwp">
              <el-input
                v-model="taskForm.sfGwp"
                clearable
                placeholder="请输入"
                v-positive-only:5
                @wheel.stop.prevent
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="NF₃气体GWP值：" prop="nfGwp">
              <el-input
                v-model="taskForm.nfGwp"
                clearable
                placeholder="请输入"
                v-positive-only:5
                type="number"
                @wheel.stop.prevent
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="content-header">
          <span class="g-font-14n1b">HFCs&PFCs气体特殊因子</span>
        </div>
        <div class="factor-list">
          <div class="factor-list-item" v-for="(item, index) in taskForm.hpGwp" :key="index">
            <el-select
              class="item-select"
              v-model="item.factorNo"
              filterable
              remote
              placeholder="请选择适用因子"
              :remote-method="remoteMethod"
              @visible-change="handleVisibleChange"
              value-key="index"
            >
              <template #prefix>
                <CIcon style="color: #5f6677" type="c-xian-sousuo"></CIcon>
              </template>
              <el-option
                v-for="item in selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-form-item prop="gwp" style="margin: 0 !important">
              <el-input
                class="item-input"
                v-model="item.gwp"
                clearable
                placeholder="请输入GWP值"
                v-positive-only:5
                type="number"
                @wheel.stop.prevent
              >
              </el-input>
            </el-form-item>
            <div class="item-close" @click="handleDelFactor(index)">
              <CIcon type="c-xian-cha"></CIcon>
            </div>
          </div>
          <el-button type="default" size="default" class="g-mt4" @click="addFactor"
            ><CIcon type="c-xian-xinjian" class="g-mr4"></CIcon>新增适用因子</el-button
          >
        </div>
      </el-form>
    </el-scrollbar>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'AddGwpDialog'
};
</script>
<script lang="ts" setup>
import {
  defineProps,
  withDefaults,
  defineEmits,
  computed,
  ref,
  watch,
  reactive,
  nextTick
} from 'vue';
import { CDialog } from '@/components/CDialog/index';
import { rules } from './rules';
import { useMessage } from '@/hooks/useMessage';
import type { ElScrollbar } from 'element-plus';
import { getFactorOptions } from '@/apis/system/config/relationship';
import { getGwpDetail, addGwp, editGwp, getGwpVersionList } from '@/apis/system/config/gwp';
import { IhpGwp, IGwpVersionResult } from '@/apis/system/config/model/gwpModel';

interface SelectFillTypeDialogProps {
  visible: boolean;
  gwpId: string | number;
}
const props = withDefaults(defineProps<SelectFillTypeDialogProps>(), {});
const emit = defineEmits(['update:visible', 'refresh']);
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (visible) {
      if (props.gwpId) {
        loadData(props.gwpId);
      } else {
        init();
      }
    } else {
      remoteMethod('');
    }
  }
);
const selectOptions = ref<any[]>([]);
const versionList = ref<IGwpVersionResult[]>([]);
const formRef = ref();
const loading = ref(false);
const pageLoading = ref(false);
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>();
const { createMessage } = useMessage();
const taskForm = reactive({
  gwpCode: '',
  coGwp: '',
  chGwp: '',
  noGwp: '',
  hpGwp: [] as IhpGwp[],
  sfGwp: '',
  nfGwp: ''
});
const init = () => {
  // formRef.value?.resetFields();
  taskForm.hpGwp = [];
  taskForm.gwpCode = '';
  taskForm.coGwp = '';
  taskForm.chGwp = '';
  taskForm.noGwp = '';
  taskForm.sfGwp = '';
  taskForm.nfGwp = '';
};
const loadVersionList = async () => {
  let data = await getGwpVersionList();
  versionList.value = data ?? [];
};
loadVersionList();
const loadData = async (gwpId: string | number) => {
  pageLoading.value = true;
  try {
    let data = await getGwpDetail(gwpId);
    taskForm.gwpCode = data.gwpCode;
    taskForm.coGwp = data.coGwp;
    taskForm.chGwp = data.chGwp;
    taskForm.noGwp = data.noGwp;
    taskForm.sfGwp = data.sfGwp;
    taskForm.nfGwp = data.nfGwp;
    taskForm.hpGwp = data.hpGwp;
  } finally {
    pageLoading.value = false;
  }
};
const remoteMethod = (query: string) => {
  getFactorOptions(query).then(res => {
    const ans = res.map(item => {
      return {
        label: item.factorDataString,
        value: item.factorNo
      };
    });
    selectOptions.value = ans;
  });
};
remoteMethod('');
const handleVisibleChange = (val: any) => {
  console.log('val', val);
  if (val) {
    remoteMethod('');
  }
};
const handleDelFactor = (index: number) => {
  taskForm.hpGwp.splice(index, 1);
};
const addFactor = () => {
  taskForm.hpGwp.push({
    factorNo: '',
    gwp: ''
  });
  nextTick(() => {
    scrollToBottom();
  });
};
const scrollToBottom = () => {
  const wrap: any = scrollbarRef.value?.wrapRef;
  let max = wrap?.scrollHeight - wrap?.clientHeight;
  scrollbarRef.value?.setScrollTop(max);
};
const handleConfirm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 校验
      let arr: IhpGwp[] = [];
      if (taskForm.hpGwp.length) {
        arr = taskForm.hpGwp.filter((item: IhpGwp) => {
          return item.gwp !== '' || item.factorNo !== '';
        });
        for (let item of arr) {
          if ((item.gwp && !item.factorNo) || (!item.gwp && item.factorNo)) {
            return createMessage.error('HFCs&PFCs气体未填写完整！');
          }
        }
      }
      taskForm.hpGwp = arr;
      if (props.gwpId) {
        await editGwp({ ...taskForm, gwpId: props.gwpId });
        createMessage.success('编辑成功！');
      } else {
        await addGwp(taskForm);
        createMessage.success('新增成功！');
      }
      dialogVisible.value = false;
      emit('refresh');
    }
  });
};
</script>
<style lang="scss" scoped>
.content-header {
  width: 100%;
  height: 44px;
  background: #fff;
  padding: 0 20px;
  display: flex;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 1;
}
.edit-container {
  padding: 0 0 0 20px;
}
:deep(.el-form-item) {
  margin-right: 20px !important;
  .el-cascader,
  .el-autocomplete,
  .el-select {
    width: 100%;
  }
  .el-input-group--append {
    .el-input__wrapper {
      width: calc(100% - 1px);
    }
  }
  .el-input-group__append {
    width: 66px;
    .el-input__wrapper {
      padding-right: 0px;
    }
    .el-input__suffix {
      right: 14px;
    }
  }
  .label {
    display: inline-block;
    width: 94px;
    text-align: left;
    font-size: 14px;
    color: #51596c;
  }
  .des {
    font-size: 14px;
    color: #212529;
    display: inline-block;
  }
}
.factor-list {
  padding: 0 20px 20px;
}
.factor-list-item {
  margin-bottom: 8px;
  display: flex;
  justify-content: flex-start;
  .item-select {
    width: 330px;
  }

  .item-input {
    width: 160px;
    margin: 0 8px;
  }
  .item-close {
    cursor: pointer;
    width: 32px;
    height: 32px;
    background: #ffffff;
    box-shadow: 0px 2px 2px 0px rgba(230, 230, 230, 0.2);
    border-radius: 2px;
    border: 1px solid #e4e7ed;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>

<style lang="scss">
.gwp-dialog .c-dialog__body-wrapper {
  padding: 0 !important;
}
</style>
